package com.doit.demo.day05;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.*;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

/**
 * @DATE 2022/2/19/10:05
 * @Author MDK
 * @Version 2021.2.2
 *
 * 所有的window,按照是否key后再进行划分窗口,分为keyedWindow和NonKeyedWindow
 *      如果没有KeyBy就划分窗口,就是NonKeyedWindow,
 *      底层调用的就是windowAll方法,window和window operator对应的Task并行度永远为1
 *
 *      KeyBy后划分的countWindow是多并行的,当一个组中的数据条数达到指定数量后,该组数据单独触发
 *
 **/
public class CountWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> lines = env.socketTextStream("linux01", 8888);
        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String line) throws Exception {
                String[] fields = line.split(",");
                String word = fields[0];
                int count = Integer.parseInt(fields[1]);
                return Tuple2.of(word, count);
            }
        });

        //先进行keyBy,再划分窗口,当窗口中的数据条数达到一定数量后再进行输出
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = wordAndCount.keyBy(t -> t.f0);
        WindowedStream<Tuple2<String, Integer>, String, GlobalWindow> windowedStream = keyedStream.countWindow(5);
        //划分窗口后,需要调用相应的方法
        SingleOutputStreamOperator<Tuple2<String, Integer>> operator = windowedStream.sum(1);

        operator.print();
        env.execute();
    }
}
